package utils;

import helper.GlobalConfig;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpConfigStorage;
import me.chanjar.weixin.cp.api.WxCpInMemoryConfigStorage;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import models.admin.AdminUser;
import models.admin.enums.AdminUserType;
import models.enums.WxcpAppType;
import models.issue.Issue;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import util.common.ConvertUtil;

import java.util.Date;
import java.util.List;

/**
 * Created by LiuBin on 2017/3/1.
 */
public class WxCpMsgUtil {
    private static WxCpInMemoryConfigStorage qyWxCpConfigStorage;

    /**
     * 物业管理wxCp配置.
     */
    private static WxCpConfigStorage getWyWxCpConfigStorage() {
        if (qyWxCpConfigStorage == null) {
            qyWxCpConfigStorage = new WxCpInMemoryConfigStorage();

            qyWxCpConfigStorage.setCorpId(GlobalConfig.WXCP_CORPID);
            qyWxCpConfigStorage.setCorpSecret(GlobalConfig.WXCP_SECRET);  // 设置微信企业号的app corpSecret
            qyWxCpConfigStorage.setAesKey(GlobalConfig.WXCP_WY_AESKEY);      // 设置微信企业号应用的EncodingAESKey
            qyWxCpConfigStorage.setToken(GlobalConfig.WXCP_WY_TOKEN);       // 设置微信企业号应用的token
            qyWxCpConfigStorage.setAgentId(GlobalConfig.WXCP_WY_AGENT_ID);     // 设置微信企业号应用ID
            qyWxCpConfigStorage.setOauth2redirectUri("http://" + GlobalConfig.WEIXIN_BASE_DOMAIN);
        }
        return qyWxCpConfigStorage;
    }
    public static WxCpConfigStorage getWxCpConfigStorage(WxcpAppType wxcpAppType) {
        Logger.info("LOG00010: query wxcpAppType=" + wxcpAppType);
        switch (wxcpAppType) {
            case WY:
                return getWyWxCpConfigStorage();
        }
        return getWyWxCpConfigStorage();
    }
    /**
     * 通过ConfigStore得到微信服务接口.
     */
    public static WxCpService getWxCpService(WxCpConfigStorage wxCpConfigStorage) {
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
        return wxCpService;
    }
    public static WxCpService getWxCpService(WxcpAppType appType) {
        return getWxCpService(getWxCpConfigStorage(appType));
    }

    public static WxCpService getWxCpService() {
        return getWxCpService(WxcpAppType.WY);
    }
    /**
     * 报修派工通知
     * @param issueId
     * @return
     */
    public static Boolean sendMsgToRepairMan(String issueId,String operator,Integer flag) {
        Boolean bol = false;
        if (StringUtils.isNotBlank(issueId)) {
            Issue issue = Issue.findByIdAndUnDeleted(issueId);
            AdminUser adminUser = AdminUser.findById(ConvertUtil.toLong(operator));
            if(adminUser==null )
                return bol;
            String openId = adminUser.cpUserId;
//            openId = "demo";//测试使用
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            Logger.info("sendMsgToRepairMan:userId:"+openId);
            String weixinUrl = Play.configuration.getProperty("weixin.url");
            if(flag == 1){
                weixinUrl  = weixinUrl+ "wxcp/issueDetailEngineer/"+issueId;
            } else {
                weixinUrl  = weixinUrl+ "wxcp/issueDetailAccept/"+issueId;
            }
            WxCpMessage.WxArticle article1 = new WxCpMessage.WxArticle();
            article1.setUrl(weixinUrl);
//            article1.setPicUrl("PIC_URL");
            article1.setDescription("报修派单通知：您好，有新的报修,"+issue.issueName+",请于"+DateUtil.dateToString(issue.visitTimeBegin == null?new Date():issue.visitTimeBegin,"yyyy-MM-dd HH:mm")
                    +"至"+DateUtil.dateToString(issue.visitTimeEnd == null?new Date():issue.visitTimeEnd,"yyyy-MM-dd HH:mm")+"内按时上门维修!");
            article1.setTitle("报修派单通知");

            WxCpMessage message = WxCpMessage.NEWS()
                    .agentId(GlobalConfig.WXCP_WY_AGENT_ID) // 企业号应用ID
                    .toUser(openId)
                    .addArticle(article1)
                    .build();
            try {
                getWxCpService().messageSend(message);
            } catch (WxErrorException e) {
                Logger.warn(e, "LOG100131: 报修派单通知失败:" + article1);
                return bol;
            }
        }
        return bol;
    }

    /**
     * 发送每月账单生成信息给财务
     * @param billNums
     * @return
     */
    public static Boolean sendBillMsgToFinance(Long billNums) {
        Boolean bol = false;
        if (billNums != null && billNums> 0) {
            List<AdminUser> adminUserList =  AdminUser.findAllAdminUserByTypeAndCompany(AdminUserType.FINANCE,null);
            if(adminUserList != null && adminUserList.size() > 0) {
                for(AdminUser adminUser:adminUserList) {
                    String openId = adminUser.cpUserId;
//                    openId = "demo";
                    if(StringUtils.isBlank(openId)) {
                        bol = false;
                        return bol;
                    }
                    Logger.info("sendBillMsgToFinance:userId:"+openId);
                    String currentMonth = DateUtil.dateToString(DateUtil.lastMonthOfFirstDay(),"yyyy年MM月");
                    String weixinUrl = Play.configuration.getProperty("weixin.url");
//                    weixinUrl  = weixinUrl+ "issue/issueDetail/"+issueId;
                    WxCpMessage.WxArticle article1 = new WxCpMessage.WxArticle();
                    article1.setUrl(weixinUrl);
//                    article1.setPicUrl("PIC_URL");
                    article1.setDescription("账单生成通知：您好："+currentMonth+"共"+billNums
                            +"条账单已生成，请您及时审核!");
                    article1.setTitle("账单生成通知");

                    WxCpMessage message = WxCpMessage.NEWS()
                            .agentId(GlobalConfig.WXCP_WY_AGENT_ID) // 企业号应用ID
                            .toUser(openId)
                            .addArticle(article1)
                            .build();
                    try {
                        getWxCpService().messageSend(message);
                    } catch (WxErrorException e) {
                        Logger.warn(e, "LOG100131: 账单生成通知失败:" + article1);
//                        return bol;
                    }
                }
            }
        }
        return bol;
    }

    /**
     * 发送新报修提醒给客服人员
     * @param issue
     * @return
     */
    public static Boolean sendIssueCreateToClient(Issue issue) {
        Boolean bol = false;
        if (issue != null ) {
            List<AdminUser> adminUserList =  AdminUser.findAllAdminUserByTypeAndCompany(AdminUserType.NORMAL,null);
            if(adminUserList != null && adminUserList.size() > 0) {
                for(AdminUser adminUser:adminUserList) {
                    String openId = adminUser.cpUserId;
//                    openId = "demo";
                    if(StringUtils.isBlank(openId)) {
                        bol = false;
                        return bol;
                    }
                    Logger.info("sendIssueCreateToClient:userId:"+openId);
                    String currentMonth = DateUtil.dateToString(new Date(),"yyyy年MM月dd日 hh:mm");
                    String weixinUrl = Play.configuration.getProperty("weixin.url");
//                    weixinUrl  = weixinUrl+ "issue/issueDetail/"+issueId;
                    WxCpMessage.WxArticle article1 = new WxCpMessage.WxArticle();
                    article1.setUrl(weixinUrl);
//                    article1.setPicUrl("PIC_URL");
                    article1.setDescription("新报修通知：您好：有新的报修，"+currentMonth+"【"+issue.issueName
                            +"】,请您及时审核派工!");
                    article1.setTitle("新报修通知");

                    WxCpMessage message = WxCpMessage.NEWS()
                            .agentId(GlobalConfig.WXCP_WY_AGENT_ID) // 企业号应用ID
                            .toUser(openId)
                            .addArticle(article1)
                            .build();
                    try {
                        getWxCpService().messageSend(message);
                    } catch (WxErrorException e) {
                        Logger.warn(e, "LOG100131: 新报修通知失败:" + article1);
//                        return bol;
                    }
                }
            }
        }
        return bol;
    }
}
